/**
 * 分类页面JavaScript
 */

// 分类页面管理器
window.CategoryPage = {
    // 当前页码
    currentPage: 1,

    // 总页数
    totalPages: 1,

    // 是否正在加载
    isLoading: false,

    // 是否还有更多数据
    hasMoreData: true,

    // 货币符号
    currencySymbol: $('#currency-symbol').text(),

    // 初始化
    init(currentPage, totalPages) {
        this.currentPage = currentPage;
        this.totalPages = totalPages;
        this.hasMoreData = currentPage < totalPages;

        this.bindEvents();
        this.initInfiniteScroll();
    },

    // 绑定事件
    bindEvents() {
        // 绑定全局函数
        window.showVipTip = () => this.showVipTip();
    },

    // 初始化无限滚动
    initInfiniteScroll() {
        if (!this.hasMoreData) {
            return;
        }

        window.addEventListener('scroll', () => {
            this.handleScroll();
        });
    },

    // 处理滚动事件
    handleScroll() {
        if (this.isLoading || !this.hasMoreData) {
            return;
        }

        // 检查是否滚动到触发位置（距离底部300px时开始加载）
        const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
        const windowHeight = window.innerHeight;
        const documentHeight = document.documentElement.scrollHeight;

        // 提前触发加载，改善用户体验
        if (scrollTop + windowHeight >= documentHeight - 300) {
            this.loadMoreGoods();
        }
    },

    // 加载更多商品
    loadMoreGoods() {
        if (this.isLoading || !this.hasMoreData) {
            return;
        }

        this.isLoading = true;
        this.showLoading();

        const nextPage = this.currentPage + 1;
        const currentUrl = new URL(window.location);
        currentUrl.searchParams.set('page', nextPage);
        currentUrl.searchParams.set('ajax', '1');

        $.ajax({
            url: currentUrl.toString(),
            type: 'GET',
            dataType: 'json',
            success: (response) => {
                if (response.code === 1) {
                    const data = response.data;

                    if (data.goods_list && data.goods_list.length > 0) {
                        this.appendGoods(data.goods_list);
                        this.currentPage = nextPage;

                        // 检查是否还有更多数据
                        if (this.currentPage >= this.totalPages) {
                            this.hasMoreData = false;
                            this.showNoMoreData();
                        }
                    } else {
                        this.hasMoreData = false;
                        this.showNoMoreData();
                    }
                } else {
                    console.error('加载失败:', response.msg);
                    showError('加载失败: ' + (response.msg || '未知错误'), 3000);
                }
            },
            error: (xhr, status, error) => {
                console.error('网络错误:', error);
                showError('网络连接失败', 3000);
            },
            complete: () => {
                this.isLoading = false;
                this.hideLoading();
            }
        });
    },

    // 追加商品到容器
    appendGoods(goodsList) {
        const container = document.getElementById('goods-container');

        goodsList.forEach(goods => {
            // 创建响应式商品项
            const goodsHtml = this.createResponsiveGoodsItem(goods);
            container.insertAdjacentHTML('beforeend', goodsHtml);
        });
    },

    // 创建响应式商品项HTML
    createResponsiveGoodsItem(goods) {
        const imageUrl = goods.slider_image && goods.slider_image[0]
            ? goods.slider_image[0]
            : '';

        // todo 符号单位待办

        const priceHtml = goods.price
            ? `<span class="text-blue-600 font-bold price-container flex gap-1 items-center">
                   <span class="text-xs currency-symbol">${this.currencySymbol}</span>
                   <span class="md:text-lg text-base price-number">${goods.price}</span>
               </span>`
            : `<span class="text-green-600 font-bold text-base">免费</span>`;

        return `
            <a class="cursor-pointer h-full" href="${goods.url}" target="_blank">
                <div class="bg-blue-50 rounded-lg overflow-hidden hover:border-blue-200 transition-colors h-full flex flex-row md:flex-col">
                    <!-- 商品图片 -->
                    <div class="relative bg-gray-100 overflow-hidden w-20 h-20 md:w-full md:h-32 flex-shrink-0 md:aspect-w-2 md:aspect-h-1">
                        <img src="${imageUrl}"
                             alt="${goods.name}"
                             class="w-full h-full object-cover lazy-image rounded md:rounded-t-lg md:rounded-none">
                    </div>

                    <!-- 商品信息 -->
                    <div class="p-3 flex-1 flex flex-col justify-between md:justify-start">
                        <div class="text-sm font-medium text-blue-600 line-clamp-2 leading-tight md:h-10 md:leading-5 flex-1 mb-2">
                            ${goods.name}
                        </div>
                        <div class="flex items-center justify-between md:mt-2">
                            <div class="flex items-center">
                                ${priceHtml}
                            </div>
                            <div class="flex items-center space-x-1">
                                <span class="text-xs text-gray-500">
                                    <i class="fas fa-eye mr-1"></i><span class="view-count" data-count="${goods.views}">${goods.views}</span>
                                </span>
                            </div>
                        </div>
                    </div>
                </div>
            </a>
        `;
    },

    // 显示加载状态
    showLoading() {
        const loadingEl = document.getElementById('loading-more');
        if (loadingEl) {
            loadingEl.classList.remove('hidden');
        }
    },

    // 隐藏加载状态
    hideLoading() {
        const loadingEl = document.getElementById('loading-more');
        if (loadingEl) {
            loadingEl.classList.add('hidden');
        }
    },

    // 显示没有更多数据
    showNoMoreData() {
        const noMoreEl = document.getElementById('no-more-data');
        if (noMoreEl) {
            noMoreEl.classList.remove('hidden');
        }
    },

    // VIP提示
    showVipTip() {
        if (window.toast && window.toast.info) {
            window.toast.info('VIP专享功能正在开发中，敬请期待');
        } else if (typeof window.showInfo === 'function') {
            window.showInfo('VIP专享功能正在开发中，敬请期待', 3000);
        } else {
            // 使用统一的toast系统，避免使用alert
            console.log('VIP专享功能正在开发中，敬请期待');
            // 创建简单的toast提示
            this.createSimpleToast('VIP专享功能正在开发中，敬请期待', 'info');
        }
    },

    // 创建简单的toast提示（备用方案）
    createSimpleToast(message, type) {
        const toast = document.createElement('div');
        const bgColor = type === 'success' ? '#10b981' : type === 'error' ? '#ef4444' : '#3b82f6';
        toast.style.cssText = `
            position: fixed;
            top: 20px;
            right: 20px;
            background: ${bgColor};
            color: white;
            padding: 12px 20px;
            border-radius: 8px;
            font-size: 14px;
            z-index: 10000;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
            transform: translateX(100%);
            transition: transform 0.3s ease;
        `;
        toast.textContent = message;

        document.body.appendChild(toast);

        // 显示动画
        setTimeout(() => {
            toast.style.transform = 'translateX(0)';
        }, 100);

        // 自动移除
        setTimeout(() => {
            toast.style.transform = 'translateX(100%)';
            setTimeout(() => {
                if (toast.parentNode) {
                    toast.parentNode.removeChild(toast);
                }
            }, 300);
        }, 3000);
    }
};
